package com.neusoft.yiyang.gateway.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GatewayExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GatewayExceptionHandler.class);

    // 限流（HTTP 429）统一走这里
    @ExceptionHandler(ResponseStatusException.class)
    public Mono<ResponseEntity<Map<String, Object>>> handleTooMany(ResponseStatusException e) {
        if (e.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
            logger.warn("限流触发: {}", e.getMessage());
            Map<String, Object> result = new HashMap<>();
            result.put("code", 429);
            result.put("message", "请求过于频繁，请稍后再试");
            return Mono.just(ResponseEntity
                    .status(HttpStatus.TOO_MANY_REQUESTS)
                    .body(result));
        }
        return Mono.error(e);
    }

    // 路由未找到
    @ExceptionHandler(NotFoundException.class)
    public Mono<ResponseEntity<Map<String, Object>>> handleNotFound(NotFoundException e) {
        logger.error("路由未找到: {}", e.getMessage(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 404);
        result.put("message", "服务未找到");
        return Mono.just(ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(result));
    }

    // 其它异常
    @ExceptionHandler(Exception.class)
    public Mono<ResponseEntity<Map<String, Object>>> handleAll(Exception e) {
        logger.error("系统异常: {}", e.getMessage(), e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", "网关服务异常，请稍后再试");
        return Mono.just(ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(result));
    }
}
